using System;
using Crowler.Model.CoreComponents.DataAccess;
using NHibernate;

namespace CoreComponents.DataAccess
{
    public class DataAccessManager : IDataAccessManager
    {
        private readonly IUnitOfWorkFactory _unitOfWorkFactory;
        private IUnitOfWork _innerUnitOfWork;
        
        private const string UnitOfWorkNotExistExceptionMessage = "You are not in a unit of work.";
        private const string CantStartMoreThenOneExceptionMessage = "You cannot start more than one unit of work at the same time.";


        public DataAccessManager(IUnitOfWorkFactory unitOfWorkFactory)
        {
            _unitOfWorkFactory = unitOfWorkFactory;
        }

        public IUnitOfWork Start()
        {
            if (_innerUnitOfWork != null)
                throw new InvalidOperationException(CantStartMoreThenOneExceptionMessage);
            _innerUnitOfWork = _unitOfWorkFactory.Create();
            return _innerUnitOfWork;
        }

        public IUnitOfWork Current
        {
            get
            {
                if (_innerUnitOfWork == null)
                    throw new InvalidOperationException(UnitOfWorkNotExistExceptionMessage);
                return _innerUnitOfWork;
            }
        }
        public bool IsStarted
        {
            get {return _innerUnitOfWork != null; }
        }

        public ISession CurrentSession
        {
            get { return _unitOfWorkFactory.CurrentSession; }
            internal set { _unitOfWorkFactory.CurrentSession = value; }
        }

        public void DisposeUnitOfWork(IUnitOfWork unitOfWorkImplementor)
        {
            
        }
    }
}